Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

题目大意:判断给定二叉树是不是平衡二叉树

题目难度:Easy

/**
 * Created by gzdaijie on 16/6/9
 */
public class Solution {
    public boolean isBalanced(TreeNode root) {
        return helper(root) >= 0;
    }

    private int helper(TreeNode root) {
        if (root == null) return 0;
        int left, right;

        left = helper(root.left);
        if (left < 0) return -1;
        right = helper(root.right);
        if (right < 0 || Math.abs(left - right) > 1) return -1;
        return Math.max(left, right) + 1;
    }
}
gzdaijie            updated 2016-06-09 01:43:59

results matching ""

    No results matching ""